<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="请输入类别关键字" v-model="search.name">
      </el-input>
      <el-button class="filter-item" type="primary" plain v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <!-- <el-button class="filter-item" style="margin-left: 10px;" v-roles="'allotCategory'" @click="addVisible = true" v-waves  type="primary" icon="el-icon-edit">添加主类栏目</el-button> -->
      <el-button class="filter-item" style="margin-left: 10px;" v-roles="'allotCategory'" @click="handleAllot" v-waves type="primary" icon="el-icon-edit">分配类别</el-button>
    </div>

 <el-table :data="listData" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%" @cell-dblclick='tableDbEdit'>
    
      <el-table-column width="150px" align="center" label="排序">
        <template slot-scope="scope">
          <span>
              <el-input @blur="handleBlur(scope.row)" style="width: 80px;" class="filter-item" placeholder="排序" v-model="scope.row.sort"></el-input>
          </span>
        </template>
      </el-table-column>

      <el-table-column min-width="120px" label="栏目名称">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="90px" label="可得比例(模块)%">
        <template slot-scope="scope">
          <!-- <span v-if="cellShow"><el-input @change="changePercent(scope.row)" v-model="scope.row.percent_num" type='number' min="0.00" step="0.01" max="100"></el-input></span> -->
          <!-- <span v-else @click="cellShow=true" style="color:#FF0000;font-size:16px">{{scope.row.percent_num}}%</span> -->
          <span>{{scope.row.percent_num}}</span>
        </template>
      </el-table-column>

      <el-table-column  width="180px" label="归属代理">
        <template slot-scope="scope">
          <span>{{scope.row.reseller_name}}</span>
        </template>
      </el-table-column>

      <el-table-column  width="120px" label="24H营业状态">
        <template slot-scope="scope">
          <el-button size="mini" :type="scope.row.isdaily | statusFilter" plain @click="handleOpenState(scope.row)">{{scope.row.isdaily | openName}}</el-button>
        </template> 
      </el-table-column>

      <el-table-column class-name="status-col" label="状态" width="100">
        <template slot-scope="scope">
           <el-tag :type="scope.row.status | statusFilter">{{scope.row.status | statusName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status==2" size="mini" @click="handleModifyStatus(scope.row,'1')">显示</el-button>
          <el-button v-if="scope.row.status==1" size="mini" @click="handleModifyStatus(scope.row,'2')">下架</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handlDel(scope.row)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div> -->

    <!-- 弹框分配栏目 -->
    <el-dialog title="分配类别到店" :visible.sync="allotVisible">
    <el-transfer filterable :filter-method="filterMethod" filter-placeholder="请输入类别名称" v-model="transferVal" :data="transferData"  :titles="['仓库', '自营店']"></el-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="allotButton">确认分配</el-button>
      </span>
    </el-dialog>
    <!-- 弹框分配栏目  end -->
    <!-- 弹框添加-->
    <el-dialog title="添加类别" :visible.sync="addVisible">
        <el-form :rules="rules" ref="tempForm" :model="addTemp" label-position="left" label-width="80px" style='width: 400px; margin-left:60px;'  class="demo-ruleForm">
          <el-form-item label="栏目名称" prop="name">
            <el-input  class="filter-item" placeholder="商品类别名称" v-model="addTemp.name"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status">
          <el-radio-group v-model="addTemp.status">
            <el-radio label="0">隐藏栏目</el-radio>
            <el-radio label="1">显示栏目</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="addLoading" @click="handleCreate">确认添加</el-button>
      </span>
    </el-dialog>
    <!-- 弹框添加  end -->

    <!-- 代理商添加弹框 start-->
    <el-dialog title="代理分配" :visible.sync="editVisible"  width="35%">
        <el-form  ref="resellerForm" :model="addReseller" label-position="left" label-width="80px" style='margin-left:40px;'  class="demo-ruleForm">
          <el-form-item label-width="75px" label="选择代理:" class="postInfo-container-item">
            <el-select clearable class="filter-item" filterable  v-model="addReseller.reseller_id" placeholder="选择商品代理,无则不选">
              <el-option v-for="item in  adminOptions" :key="item.id" :label="item.username" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="addLoading" @click="handleUpdate('saveBtn')">确认添加</el-button>
      </span>
    </el-dialog>
    <!-- 代理商添加弹框  end -->

    <!--可自定义按钮的样式、show/hide临界点、返回的位置  -->
    <!--如需文字提示，可在外部添加element的<el-tooltip></el-tooltip>元素  -->
    <el-tooltip placement="top" content="回到顶部">
      <back-to-top transitionName="fade" :customStyle="myBackToTopStyle" :visibilityHeight="300" :backPosition="50"></back-to-top>
    </el-tooltip>
  </div>
</template>
<script>
import waves from '@/directive/waves' // 水波纹指令
import { mapGetters } from 'vuex'
import BackToTop from '@/components/BackToTop' // 回到顶部
import * as api from '@/api/main-api' // API

export default {
  name: 'Category',
  directives: {
    waves
  },
  components: { BackToTop },

  data() {
    return {

      transferData: [],
      transferVal: [],
      // 回到顶部样式
      myBackToTopStyle: {
        right: '50px',
        bottom: '50px',
        width: '40px',
        height: '40px',
        'border-radius': '4px',
        'line-height': '45px', // 请保持与高度一致以垂直居中
        background: '#e7eaf1'// 按钮的背景颜色
      },
      listQuery: {
        page: 1,
        pagesize: 10,
        unit_id: 0
      },
      // 搜索
      search: {
        name: ''
      },
      addTemp: {
        name: '',
        status: '1', // 默认显示
        unit_id: '0'
      },
      // 编辑/分配代理
      addReseller: {
        reseller_id: 0,
        reseller_name: ''
      },

      // 代理列表
      adminOptions: [],
      // 规则
      rules: {
        name: [
          { required: true, message: '请输入栏目名称', trigger: 'blur' },
          { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur' }
        ]
      },
      listData: [],
      listLoading: false,
      addLoading: false,
      allotVisible: false,
      addVisible: false,
      editVisible: false // 分配代理编辑
      // cellShow: false
      // total: 0
    }
  },

  // 装换属性
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'info',
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    },
    statusName(status) {
      return (status === '1') ? '显示中' : (status === '2') ? '已隐藏' : '未知'
    },
    openName(status) {
      return (status === '1') ? '开店营业' : (status === '2') ? '24H营业' : '未知'
    }
  },

  computed: {
    ...mapGetters(['outlet_id'])
  },

  // 初始化数据
  created() {
    this.listQuery.unit_id = this.outlet_id
    setTimeout(() => {
      this.fetchData()
    }, 20)
    this.reselelrInfo() // 代理选择
  },

  methods: {
    // 获取数据
    fetchData() {
      this.listLoading = true
      this.listQuery = Object.assign(this.listQuery, this.search)
      return new Promise((resolve, reject) => {
        api.categoryApi(this.listQuery).then(response => {
          if (response.data.code === 0) {
            this.listData = response.data.data
          }
          this.listLoading = false
        })
      })
    },

    // 搜索
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },

    // 排序
    handleBlur(row) {
      var data = {
        id: row.id,
        unit_id: this.outlet_id, // 添加属性
        field: 'sort', // 修改单个字段
        types: 'hotelCategory',
        status: row.sort // 值,
      }
      this.postFieldStatus(data, row)
      row.sort = data.status
    },

    // 编辑按钮
    handleUpdate(row) {
      if (row === 'saveBtn') { // 提交按钮
        const _this = this

        this.adminOptions.filter(function(item, indexs) {
          if (item.id === _this.addReseller.reseller_id) {
            _this.addReseller.reseller_name = item.username
            return
          }
        })
        // 提交数据
        api.resellerCategoryApi(this.addReseller).then(response => {
          if (response.data.code === 0) {
            this.fetchData()
            this.$root.message('操作成功', 'success')
          }
        })
        this.editVisible = false
      } else {
        this.editVisible = true // 编辑弹框
        this.addReseller.reseller_id = row.reseller_id
        this.addReseller.id = row.id
      }
    },

    // 获取商品代理列表
    reselelrInfo() {
      var data = {
        unit_id: this.outlet_id, // 添加属性
        role_type: 3
      }
      api.adminSelectApi(data).then(response => {
        if (response.data.code === 0) {
          this.adminOptions = response.data.data
        }
      })
    },

    // 双击修改 弹出input
    tableDbEdit(row, column, cell, event) {
      var _this = this
      if (column.label === '可得比例(模块)%') {
        const value_event = event.target.innerHTML
        event.target.innerHTML = ''
        const cellInput = document.createElement('input')
        cellInput.value = value_event
        cellInput.setAttribute('type', 'number')
        cellInput.setAttribute('max', '100')
        cellInput.setAttribute('step', '0.01')
        cellInput.setAttribute('min', '0.00') // min="0.00" step="0.01" max="100"
        cellInput.style.width = '100%'
        cell.appendChild(cellInput)

        cellInput.onblur = function() {
          cell.removeChild(cellInput)
          event.target.innerHTML = cellInput.value
          _this.changePercent(row, cellInput.value)
        }
      }
    },

    // 独立板块比例设置 2018-12-11
    changePercent(row, v) {
      var data = {
        id: row.id,
        unit_id: row.hotel_id, // 添加属性
        field: 'percent_num', // 修改单个字段
        types: 'hotelCategory',
        status: v // 值,
      }
      this.postFieldStatus(data, row)
      row.percent_num = data.status
    },

    // 修改状态
    handleModifyStatus(row, status) {
      var data = {
        status: status,
        id: row.id,
        unit_id: this.outlet_id, // 添加属性
        field: 'status', // 修改单个字段
        types: 'hotelCategory'
      }
      this.postFieldStatus(data, row)
      row.status = data.status
    },

    // 修改单个开店类型营业状态
    handleOpenState(row) {
      var data = {
        id: row.id,
        unit_id: this.outlet_id, // 添加属性
        field: 'isdaily', // 修改单个字段
        status: (row.isdaily === '1') ? '2' : '1',
        types: 'hotelCategory'
      }
      this.postFieldStatus(data, row)
      row.isdaily = data.status
    },

    // 添加栏目
    handleCreate() {
      this.$refs.tempForm.validate(valid => {
        if (valid) {
          this.addLoading = true
          api.editCategoryApi(this.addTemp).then(response => {
            if (response.data.code === 0) {
              this.fetchData()
              this.$root.message('操作成功', 'success')
            }
          })
          this.addVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
        this.addLoading = false
      })
    },

    // 删除操作
    handlDel(row) {
      this.$confirm('此操作将永久删除, 商品将全部下架是否继续?', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var data = {
          id: row.id,
          unit_id: this.outlet_id // 添加属性
        }
        api.delCategoryApi(data).then(response => {
          if (response.data.code === 0) {
            this.$root.message('删除成功', 'success')
            const index = this.listData.indexOf(row)
            this.listData.splice(index, 1)
          }
        })
      }).catch(() => {
        this.$root.message('已取消删除', 'info')
      })
    },

    // 改变总状态02版(统一)
    postFieldStatus(data, row) {
      api.stateApi(data).then(response => {
        if (response.data.code === 0) {
          this.$root.message('操作成功', 'success')
        }
      })
    },
    // 点击分配弹框
    handleAllot() {
      this.allotVisible = true
      const datas = []
      const uniTypes = []
      return new Promise((resolve, reject) => {
        api.commCategoryApi(this.listQuery).then(response => {
          // 已经存在的则不可选择
          if (response.data.code === 0) {
            this.listData.forEach((uniType, index) => {
              uniTypes.push(
                uniType.category_id
              )
            })
            response.data.data.forEach((type, index) => {
              datas.push({
                label: type.name,
                key: type.id,
                disabled: uniTypes.indexOf(type.id) >= 0
              })
            })
            this.transferData = datas
          }
        })
      })
    },

    // 自定义搜索方法
    filterMethod(query, item) {
      return item.label.indexOf(query) > -1
    },

    // 提交分配
    allotButton() {
      if (this.transferVal.length <= 0) {
        this.$root.message('请先选择类别', 'error')
        return false
      }
      var data = {
        id: this.transferVal.join(','),
        unit_id: this.outlet_id // 添加属性
      }
      api.allotCategoryApi(data).then(response => {
        if (response.data.code === 0) {
          this.$root.message('操作成功', 'success')
        }
        this.transferData = []
        this.fetchData()
      })
      this.allotVisible = false
    }

    // // 改变页条数
    // handleSizeChange(val) {
    //   this.listQuery.pagesize = val
    // },
    // // 跳页
    // handleCurrentChange(val) {
    //   this.listQuery.page = val
    // }

  },

  // 监事事件
  watch: {
    outlet_id(id) {
      this.$nextTick(() => {
        setTimeout(() => {
          this.listQuery.unit_id = id
          this.fetchData()
        }, 100)
      })
    }

  }

}
</script>
